<template>
  <el-card>
    <!-- Tab切换 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="C类客户等级管理" name="C">
        <div class="toolbar">
          <el-button type="primary" @click="onAdd">新增等级</el-button>
          <el-button type="success" @click="onPushToApp">发送到APP</el-button>
        </div>
        <el-table :data="sortedLevelList" border stripe style="margin-top: 16px;">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="等级名称" width="120" />
          <el-table-column prop="icon" label="等级图标" width="100">
            <template #default="scope">
              <el-avatar :src="scope.row.icon" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="升级所需经验值">
            <template #default="scope">
              <span v-if="scope.row.maxExp !== null && scope.row.maxExp !== undefined">
                {{ scope.row.minExp }} ≤ 经验值 < {{ scope.row.maxExp }}
              </span>
              <span v-else>
                {{ scope.row.minExp }} 及以上
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="rights" label="等级权益">
            <template #default="scope">
              <el-tag v-for="r in scope.row.rights" :key="r.type + r.value" class="mr-4">{{ r.type }}：{{ r.value }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="80" />
          <!-- 删除错误添加的等级权益列 -->
          <!-- <el-table-column label="等级权益" width="300">
            <template #default="scope">
              <div class="rights-container">
                <div>竞拍额度: {{ scope.row.rights.auctionLimit }}</div>
                <div>信用倍数: {{ scope.row.rights.creditMultiplier }}</div>
                <div>积分返利: {{ scope.row.rights.pointsRebate }}</div>
                <div>仓储期限: {{ scope.row.rights.storagePeriod }}</div>
                <div v-if="scope.row.rights.exchangeRateDiscount">汇率优惠: 有</div>
                <div v-else>汇率优惠: 无</div>
              </div>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="onEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
              <el-button size="small" type="primary" @click="onConvertToB(scope.row)">转为B类</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <!-- B类客户等级管理 -->
      <el-tab-pane label="B类客户等级管理" name="B">
        <div class="toolbar">
          <div class="toolbar-left">
            <el-button type="primary" @click="onAddBLevel">新增等级</el-button>
            <el-button type="success" @click="onPushToApp">发送到APP</el-button>
          </div>
          <!-- 删除工具栏右侧的计算方式选择 -->
          <!-- <div class="toolbar-right">
            <el-checkbox-group v-model="bTypeBasis" size="small">
              <el-checkbox label="recharge">累计充值金额</el-checkbox>
              <el-checkbox label="consume">累计消费金额</el-checkbox>
            </el-checkbox-group>
          </div> -->
        </div>
        
        <!-- B类等级权益表格 -->
        <!-- <div style="margin-bottom: 8px; color: #888; font-size: 13px;">
          金额区间为左闭右开，即 minAmount ≤ 金额 < maxAmount，最大金额留空表示无上限。
        </div> -->
        <el-table :data="sortedBLevelList" border stripe style="margin-top: 8px;">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="等级名称" width="120" />
          <el-table-column prop="icon" label="等级图标" width="100">
            <template #default="scope">
              <el-avatar :src="scope.row.icon" size="small" />
            </template>
          </el-table-column>
          <!-- 添加计算方式列 -->
          <el-table-column label="计算方式" width="180">
            <template #default="scope">
              <div v-if="bTypeBasis.includes('recharge')">累计充值金额</div>
              <div v-if="bTypeBasis.includes('consume')">累计消费金额</div>
            </template>
          </el-table-column>
          <el-table-column label="金额区间" width="180">
            <template #default="scope">
              <span v-if="scope.row.maxAmount !== null && scope.row.maxAmount !== undefined">
                {{ scope.row.minAmount }} ≤ 金额 < {{ scope.row.maxAmount }} 万円
              </span>
              <span v-else>
                {{ scope.row.minAmount }} 万円及以上
              </span>
            </template>
          </el-table-column>
          // 添加等级权益列
          <el-table-column label="等级权益" width="250">
            <template #default="scope">
              <div class="rights-container">
                <div v-if="scope.row.rights?.auctionLimit" class="right-item">竞拍额度倍: {{ scope.row.rights.auctionLimit }}</div>
                <div v-if="scope.row.rights?.creditMultiplier" class="right-item">信用倍数: {{ scope.row.rights.creditMultiplier }}</div>
                <div v-if="scope.row.rights?.pointsRebate" class="right-item">积分/返利: {{ scope.row.rights.pointsRebate }}</div>
                <div v-if="scope.row.rights?.storagePeriod" class="right-item">仓储期限: {{ scope.row.rights.storagePeriod }}</div>
                <div v-if="scope.row.rights?.exchangeRateDiscount" class="right-item">汇率优惠: 是</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="80" />
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" @click="onEditBLevel(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="onDeleteBLevel(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="showForm" :title="form.id ? '编辑等级' : '新增等级'" width="500px" style="overflow: visible;">
              <el-form :model="form" label-width="90px" :rules="rules" ref="formRef" style="padding: 0 20px;">
        <el-form-item label="等级名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="等级图标" prop="icon">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-change="handleAvatarChange"
          >
            <img v-if="form.icon" :src="form.icon" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="升级所需经验值" prop="exp" style="white-space: nowrap;">
          <el-input-number v-model="form.exp" :min="0" />
        </el-form-item>
        <el-form-item label="最小经验值" prop="minExp">
          <el-input-number v-model="form.minExp" :min="0" />
        </el-form-item>
        <el-form-item label="最大经验值" prop="maxExp">
          <el-input-number v-model="form.maxExp" :min="0" />
          <div style="font-size:12px;color:#999;">最大经验值留空表示无上限</div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="1" />
        </el-form-item>

        <el-form-item label="等级权益详情" style="white-space: nowrap;">
          <el-input
            v-model="form.desc"
            type="textarea"
            :rows="6"
            placeholder="请输入等级权益详情内容..."
            style="min-height: 120px;"
          />
        </el-form-item>
        <el-form-item label="等级权益">
          <el-button size="small" @click="showRightsDialog = true">设置权益</el-button>
          <div v-if="form.rights && form.rights.length" style="margin-top: 8px;">
            <el-tag v-for="r in form.rights" :key="r.type + r.value" class="mr-4">{{ r.type }}：{{ r.value }}</el-tag>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showForm = false">取消</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
      </template>
    </el-dialog>
    <!-- 权益设置弹窗 -->
    <el-dialog v-model="showRightsDialog" title="设置等级权益" width="480px">
      <el-form :model="rightForm" label-width="80px">
        <el-form-item label="权益类型">
          <el-select v-model="rightForm.type" placeholder="请选择">
            <el-option v-for="t in rightTypes" :key="t" :label="t" :value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="参数/数值">
          <template v-if="rightForm.type === '优惠券'">
            <el-select v-model="rightForm.value" placeholder="请选择优惠券">
              <el-option v-for="c in couponList" :key="c.id" :label="c.name" :value="c.name" />
            </el-select>
          </template>
          <template v-else-if="rightForm.type === '购物折扣'">
            <el-input v-model="rightForm.value" placeholder="如9.5折" />
          </template>
          <template v-else-if="rightForm.type === '免运费'">
            <el-input v-model="rightForm.value" placeholder="如每月2次" />
          </template>
          <template v-else>
            <el-input v-model="rightForm.value" placeholder="请输入参数/数值" />
          </template>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="rightForm.desc" placeholder="详细说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRightsDialog = false">取消</el-button>
        <el-button type="primary" @click="onAddRight">添加</el-button>
      </template>
      <div v-if="form.rights && form.rights.length" style="margin-top: 16px;">
        <el-table :data="form.rights" size="small" border>
          <el-table-column prop="type" label="类型" width="100" />
          <el-table-column prop="value" label="参数/数值" width="120" />
          <el-table-column prop="desc" label="描述" />
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button size="small" type="danger" @click="onRemoveRight(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 权益详情弹窗 -->
    <el-dialog v-model="showDescDialog" title="等级权益详情" width="500px">
      <div style="min-height:180px; background:#f8f8f8; padding:16px; border-radius:6px;">{{ currentDesc }}</div>
    </el-dialog>

    <!-- C类转B类客户等级弹窗 -->
    <el-dialog v-model="showConvertDialog" title="C类转B类客户等级" width="500px">
      <el-form :model="convertForm" label-width="120px">
        <el-form-item label="原C类等级">
          {{ convertForm.originalName }}
        </el-form-item>
        <el-form-item label="原经验值范围">
          {{ convertForm.originalMinExp }} - {{ convertForm.originalMaxExp || '无上限' }}
        </el-form-item>
        <el-form-item label="转换比例">
          <el-input v-model.number="convertForm.ratio" placeholder="例如：100表示100经验值=1万円"></el-input>
        </el-form-item>
        <el-form-item label="目标金额范围(万円)">
          <div class="range-input">
            <el-input v-model.number="convertForm.targetMinAmount" placeholder="最小金额"></el-input>
            <span>-</span>
            <el-input v-model.number="convertForm.targetMaxAmount" placeholder="最大金额(可选)"></el-input>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showConvertDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmConversion">确认转换</el-button>
      </template>
    </el-dialog>

    <!-- B类等级新增/编辑弹窗 -->
    <el-dialog v-model="showBForm" :title="bForm.id ? '编辑B类等级' : '新增B类等级'" width="800px" style="overflow: visible;">
      <el-form :model="bForm" label-width="120px" :rules="bRules" ref="bFormRef" style="padding: 0 20px;">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="等级名称" prop="name">
              <el-input v-model="bForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级图标" prop="icon">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-change="handleBLevelAvatarChange"
              >
                <img v-if="bForm.icon" :src="bForm.icon" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="最小金额" prop="minAmount">
              <el-input-number v-model="bForm.minAmount" :min="0" placeholder="0" />
              <span style="margin-left: 8px;">万円</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大金额" prop="maxAmount">
              <el-input-number v-model="bForm.maxAmount" :min="0" placeholder="999" />
              <span style="margin-left: 8px;">万円</span>
              <div style="font-size:12px;color:#999;">最大金额留空表示无上限</div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="bForm.sort" :min="1" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 添加计算方式选择 -->
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="计算方式">
              <el-checkbox-group v-model="bTypeBasis" size="small">
                <el-checkbox label="recharge">累计充值金额</el-checkbox>
                <el-checkbox label="consume">累计消费金额</el-checkbox>
              </el-checkbox-group>
              <div style="font-size:12px;color:#999;margin-top:4px;">请至少选择一种计算方式</div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- B类等级权益设置 -->
        <el-divider content-position="left">等级权益设置</el-divider>
        
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="竞拍件数">
              <el-input v-model="bForm.rights.auctionItems" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="竞拍额度倍">
              <el-select v-model="bForm.rights.auctionLimit" placeholder="请选择竞拍额度倍">
                <el-option v-for="option in auctionLimitOptions" :key="option.value" :label="option.label" :value="option.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="信用倍数">
              <el-input-number v-model="bForm.rights.creditMultiplier" :min="0" :max="10" :precision="1" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="拍照服务">
              <el-input v-model="bForm.rights.photoService" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="包裹转运">
              <el-input v-model="bForm.rights.packageForwarding" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓储期限">
              <el-input v-model="bForm.rights.storagePeriod" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="积分/返利">
              <el-input v-model="bForm.rights.pointsRebate" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="汇率优惠">
              <el-switch v-model="bForm.rights.exchangeRateDiscount" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠券/抽奖">
              <el-switch v-model="bForm.rights.couponLottery" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="竞拍">
              <el-switch v-model="bForm.rights.auction" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="直购">
              <el-input v-model="bForm.rights.directPurchase" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="砍价">
              <el-input v-model="bForm.rights.bargaining" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="竞拍到期提醒">
              <el-switch v-model="bForm.rights.auctionExpirationReminder" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="煤炉卖家提醒">
              <el-switch v-model="bForm.rights.mercariSellerReminder" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="showBForm = false">取消</el-button>
        <el-button type="primary" @click="onSaveBLevel">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// Tab相关
const activeTab = ref('C');
const bTypeBasis = ref<string[]>(['recharge']); // 默认为累计充值金额

// B类等级列表
const bLevelList = ref([
  {
    id: 1,
    name: '青铜VIP',
    icon: '',
    minAmount: 0,
    maxAmount: 10,  // 修改：从9.9改为10，与白银VIP的最小值保持一致
    sort: 1,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '2倍',
      creditMultiplier: 0,
      photoService: '300円/件',
      packageForwarding: '300円/包裹',
      storagePeriod: '14天',
      pointsRebate: '0.1%',
      exchangeRateDiscount: false,
      couponLottery: false,
      auction: true,
      directPurchase: '先付后拍',
      bargaining: false,
      auctionExpirationReminder: true,
      mercariSellerReminder: true
    }
  },
  {
    id: 2,
    name: '白银VIP',
    icon: '',
    minAmount: 10,
    maxAmount: 50,  // 保持不变
    sort: 2,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '3.5倍',
      creditMultiplier: 0,
      photoService: '300円/件',
      packageForwarding: '300円/包裹',
      storagePeriod: '20天',
      pointsRebate: '0.1%',
      exchangeRateDiscount: false,
      couponLottery: false,
      auction: true,
      directPurchase: '先付后拍',
      bargaining: '5件商品/天',
      auctionExpirationReminder: true,
      mercariSellerReminder: true
    }
  },
  {
    id: 3,
    name: '黄金VIP',
    icon: '',
    minAmount: 50,
    maxAmount: 100,  // 保持不变
    sort: 3,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '3.5倍',
      creditMultiplier: 0.1,
      photoService: '200円/件',
      packageForwarding: '300円/包裹',
      storagePeriod: '40天',
      pointsRebate: '0.15%',
      exchangeRateDiscount: false,
      couponLottery: false,
      auction: true,
      directPurchase: '先付后拍',
      bargaining: '10件商品/天',
      auctionExpirationReminder: true,
      mercariSellerReminder: true
    }
  },
  {
    id: 4,
    name: '钻石VIP',
    icon: '',
    minAmount: 100,
    maxAmount: 300,  // 修改：从299.9改为300，与星耀VIP的最小值保持一致
    sort: 4,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '4倍',
      creditMultiplier: 0.3,
      photoService: '100円/件',
      packageForwarding: '300円/包裹',
      storagePeriod: '无限制',
      pointsRebate: '0.15%',
      exchangeRateDiscount: true,
      couponLottery: true,
      auction: true,
      directPurchase: '先付后拍',
      bargaining: '20件商品/天',
      auctionExpirationReminder: true,
      mercariSellerReminder: true
    }
  },
  {
    id: 5,
    name: '星耀VIP',
    icon: '',
    minAmount: 300,
    maxAmount: 500,  // 修改：从499.9改为500，与王者VIP的最小值保持一致
    sort: 5,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '4倍',
      creditMultiplier: 0.5,
      photoService: '免费',
      packageForwarding: '免费',
      storagePeriod: '无限制',
      pointsRebate: '0.2%',
      exchangeRateDiscount: true,
      couponLottery: true,
      auction: true,
      directPurchase: '先拍后付,快人一步',
      bargaining: '无限制',
      auctionExpirationReminder: true,
      mercariSellerReminder: true
    }
  },
  {
    id: 6,
    name: '王者VIP',
    icon: '',
    minAmount: 500,
    maxAmount: null, // 表示500万円+
    sort: 6,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '5倍',
      creditMultiplier: 1,
      photoService: '免费',
      packageForwarding: '免费',
      storagePeriod: '无限制',
      pointsRebate: '0.2%',
      exchangeRateDiscount: true,
      couponLottery: true,
      auction: true,
      directPurchase: '先拍后付,快人一步',
      bargaining: '无限制',
      auctionExpirationReminder: true,
      mercariSellerReminder: true
    }
  }
]);

// B类等级列表排序
const sortedBLevelList = computed(() => {
  return [...bLevelList.value].sort((a, b) => a.sort - b.sort);
});

// B类等级表单
const bForm = reactive({
  id: undefined,
  name: '',
  icon: '',
  minAmount: 0,  // 改为最小金额
  maxAmount: 0,  // 改为最大金额
  desc: '',
  rights: {},
  sort: 1
});
// 将rules重命名为bRules
const bRules = {
  name: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
  minAmount: [{ required: true, message: '请输入最小金额', trigger: 'blur' }],
  maxAmount: [{ required: true, message: '请输入最大金额', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
};

const rightTypes = [
  '购物折扣', '免运费', '专属客服', '生日礼包', '专属优惠券', '积分加速', '专属商品', '会员日专享', '退换货绿色通道', '优惠券', '其他'
];

// 添加竞拍额度倍选项
const auctionLimitOptions = [
  { value: '2倍', label: '2倍' },
  { value: '3.5倍', label: '3.5倍' },
  { value: '4倍', label: '4倍' },
  { value: '5倍', label: '5倍' }
];

// mock 优惠券数据
const couponList = [
  { id: 'coupon1', name: '新用户专享50元券' },
  { id: 'coupon2', name: '全场通用10%OFF券' },
  { id: 'coupon3', name: '满200减30券' }
];

const levelList = ref([
  {
    id: 1,
    name: 'L1',
    icon: '',
    minExp: 0,  // 改为最小经验值
    maxExp: 1000,  // 改为最大经验值
    desc: '基础会员，享受9.5折优惠，每月1次免运费。',
    rights: [
      { type: '购物折扣', value: '9.5折', desc: '全场通用' },
      { type: '免运费', value: '每月1次', desc: '限中国大陆' }
    ],
    sort: 1
  },
  {
    id: 2,
    name: 'L2',
    icon: '',
    minExp: 1000,
    maxExp: 5000,
    desc: '高级会员，享受9折优惠，专属客服服务。',
    rights: [
      { type: '购物折扣', value: '9折', desc: '全场通用' },
      { type: '专属客服', value: '', desc: '7x24小时' }
    ],
    sort: 2
  },
  {
    id: 3,
    name: 'L3',
    icon: '',
    minExp: 5000,
    maxExp: 10000,
    desc: 'VIP会员，享受8.5折优惠，专属客服和生日礼包。',
    rights: [
      { type: '购物折扣', value: '8.5折', desc: '全场通用' },
      { type: '专属客服', value: '', desc: '7x24小时' },
      { type: '生日礼包', value: '专属礼包', desc: '生日当月' }
    ],
    sort: 3
  },
  {
    id: 4,
    name: 'L4',
    icon: '',
    minExp: 10000,
    maxExp: null,  // null表示无上限
    desc: '钻石会员，享受8折优惠，专属客服、生日礼包和专属商品。',
    rights: [
      { type: '购物折扣', value: '8折', desc: '全场通用' },
      { type: '专属客服', value: '', desc: '7x24小时' },
      { type: '生日礼包', value: '专属礼包', desc: '生日当月' },
      { type: '专属商品', value: '专属商品', desc: '限时专享' }
    ],
    sort: 4
  }
]);

// 按排序字段排序的等级列表
const sortedLevelList = computed(() => {
  return [...levelList.value].sort((a, b) => a.sort - b.sort);
});

const showForm = ref(false);
const showRightsDialog = ref(false);
const showDescDialog = ref(false);
const showBForm = ref(false);
const showConvertDialog = ref(false);
const currentDesc = ref('');
const formRef = ref();
const bFormRef = ref(); // 添加这行代码声明bFormRef变量
const form = reactive({
  id: undefined,
  name: '',
  icon: '',
  minExp: 0,
  maxExp: 0,
  desc: '',
  rights: [],
  sort: 1
});
const convertForm = reactive({
  originalName: '',
  originalMinExp: 0,
  originalMaxExp: null,
  ratio: 100, // 默认转换比例：100经验值 = 1万円
  targetMinAmount: 0,
  targetMaxAmount: null
});
const rules = {
  name: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
  minExp: [{ required: true, message: '请输入最小经验值', trigger: 'blur' }],
  maxExp: [{ required: true, message: '请输入最大经验值', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
};

function onAdd() {
  Object.assign(form, {
    id: undefined,
    name: '',
    icon: '',
    minExp: 0,
    maxExp: 0,
    desc: '请输入该等级的详细权益说明...',
    rights: [],
    sort: 1
  });
  showForm.value = true;
}
function onEdit(row: any) {
  Object.assign(form, JSON.parse(JSON.stringify(row)));
  showForm.value = true;
}
function onDelete(row: any) {
  ElMessageBox.confirm('确定要删除该等级吗？', '提示', { type: 'warning' }).then(() => {
    levelList.value = levelList.value.filter(l => l.id !== row.id);
    ElMessage.success('删除成功');
  });
}

function onSave() {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return;
    
    // 添加经验值区间验证逻辑
    const isValid = validateExpRanges();
    if (!isValid) return;

    if (form.id) {
      // 编辑
      const idx = levelList.value.findIndex(l => l.id === form.id);
      if (idx > -1) levelList.value[idx] = JSON.parse(JSON.stringify(form));
      ElMessage.success('编辑成功');
    } else {
      // 新增
      form.id = Date.now();
      levelList.value.push(JSON.parse(JSON.stringify(form)));
      ElMessage.success('新增成功');
    }
    showForm.value = false;
  });
}
// 权益设置
const rightForm = reactive({ type: '', value: '', desc: '' });
function onAddRight() {
  if (!rightForm.type || !rightForm.value) {
    ElMessage.warning('请填写完整');
    return;
  }
  if (!form.rights) form.rights = [];
  form.rights.push({ type: rightForm.type, value: rightForm.value, desc: rightForm.desc });
  rightForm.type = '';
  rightForm.value = '';
  rightForm.desc = '';
  nextTick(() => {
    showRightsDialog.value = false;
  });
}
function onRemoveRight(idx: number) {
  form.rights.splice(idx, 1);
}
// 发送到APP
function onPushToApp() {
  // 实际应调用后端接口，这里仅模拟
  ElMessage.success('已成功发送到APP');
}
// 图标上传相关
function beforeAvatarUpload(file: File) {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB');
  }
  return isImage && isLt2M;
}
function handleAvatarChange(file: any) {
  const reader = new FileReader();
  reader.onload = (e: any) => {
    form.icon = e.target.result;
  };
  reader.readAsDataURL(file.raw);
}

function onShowDesc(row: any) {
  console.log('查看权益详情:', row);
  if (row.desc && row.desc.trim()) {
    currentDesc.value = row.desc;
  } else {
    // 如果没有权益详情，则根据权益列表生成详情
    let descContent = `${row.name}等级权益详情：`;
    if (row.rights && row.rights.length > 0) {
      const rightsList = row.rights.map((right: any) => {
        return `${right.type}：${right.value || ''} ${right.desc ? `(${right.desc})` : ''}`;
      });
      descContent += rightsList.join('，');
    } else {
      descContent += '暂无设置权益';
    }
    currentDesc.value = descContent;
  }
  showDescDialog.value = true;
}

// 添加C类等级经验值范围验证函数
function validateExpRanges() {
  // 创建临时列表，包含当前表单数据
  let tempList = [...levelList.value];
  if (form.id) {
    // 编辑模式，替换原有数据
    const idx = tempList.findIndex(l => l.id === form.id);
    if (idx > -1) {
      tempList[idx] = JSON.parse(JSON.stringify(form));
    }
  } else {
    // 新增模式，添加新数据
    tempList.push(JSON.parse(JSON.stringify(form)));
  }

  // 按minExp排序
  tempList.sort((a, b) => a.minExp - b.minExp);

  let hasGap = false;

  // 检查重叠和中断
  for (let i = 0; i < tempList.length; i++) {
    const current = tempList[i];
    
    // 检查当前区间是否有效
    if (current.maxExp !== null && current.minExp >= current.maxExp) {
      ElMessage.error(`等级${current.name}的最小经验值不能大于或等于最大经验值`);
      return false;
    }

    // 检查与下一个区间是否重叠或中断
    if (i < tempList.length - 1) {
      const next = tempList[i + 1];
      
      // 如果当前区间有上限
      if (current.maxExp !== null) {
        // 检查重叠 - 不允许保存
        if (next.minExp < current.maxExp) {
          ElMessage.error(`等级${current.name}和等级${next.name}的经验值区间存在重叠，请调整`);
          return false;
        }
        
        // 检查中断 - 只提示，允许保存
        if (next.minExp > current.maxExp) {
          ElMessage.warning(`等级${current.name}和等级${next.name}的经验值区间存在中断（${current.maxExp} - ${next.minExp}）`);
          hasGap = true;
        }
      }
    }
  }

  // 存在中断但没有重叠，允许保存
  return true;
}

// Tab切换处理
function handleTabChange(tab: string) {
  activeTab.value = tab;
}

// B类等级相关函数
function onAddBLevel() {
  Object.assign(bForm, {
    id: undefined,
    name: '',
    icon: '',
    minAmount: 0,
    maxAmount: 0,
    sort: 1,
    rights: {
      auctionItems: '无限制',
      auctionLimit: '2倍',
      creditMultiplier: 0,
      photoService: '300円/件',
      packageForwarding: '300円/包裹',
      storagePeriod: '14天',
      pointsRebate: '0.1%',
      exchangeRateDiscount: false,
      couponLottery: false,
      auction: true,
      directPurchase: '先付后拍',
      bargaining: false,
      auctionExpirationReminder: true,
      mercariSellerReminder: true
    }
  });
  showBForm.value = true;
}

function onEditBLevel(row: any) {
  Object.assign(bForm, JSON.parse(JSON.stringify(row)));
  // 如果等级数据中没有计算方式，设置默认值
  if (!bTypeBasis.value || bTypeBasis.value.length === 0) {
    bTypeBasis.value = ['recharge'];
  }
  showBForm.value = true;
}

// 转换按钮点击事件
function onConvertToB(row: any) {
  // 填充转换表单数据
  convertForm.originalName = row.name;
  convertForm.originalMinExp = row.minExp;
  convertForm.originalMaxExp = row.maxExp;
  // 计算默认金额范围
  convertForm.targetMinAmount = row.minExp / convertForm.ratio;
  convertForm.targetMaxAmount = row.maxExp ? row.maxExp / convertForm.ratio : null;
  
  showConvertDialog.value = true;
}

// 确认转换
function confirmConversion() {
  // 创建B类等级数据
  const bLevelData = {
    id: undefined, // 新等级，不使用原ID
    name: convertForm.originalName + '(B类)',
    icon: '', // 可以选择保留原图标或设置新图标
    minAmount: convertForm.targetMinAmount,
    maxAmount: convertForm.targetMaxAmount,
    sort: 1, // 默认排序，可根据实际需求调整
    rights: {
      auctionItems: '无限制',
      auctionLimit: '2倍',
      creditMultiplier: 1,
      photoService: '收费',
      packageForwarding: '收费',
      storagePeriod: '30天',
      pointsRebate: '0.1%',
      exchangeRateDiscount: false,
      couponLottery: false,
      auction: true,
      directPurchase: '普通购买',
      bargaining: '限制',
      auctionExpirationReminder: false,
      mercariSellerReminder: false
    }
  };

  // 填充B类表单并打开弹窗
  Object.assign(bForm, bLevelData);
  showBForm.value = true;
  showConvertDialog.value = false;
}

function onDeleteBLevel(row: any) {
  ElMessageBox.confirm('确定要删除该等级吗？', '提示', { type: 'warning' }).then(() => {
    bLevelList.value = bLevelList.value.filter(l => l.id !== row.id);
    ElMessage.success('删除成功');
  });
}

// B类等级保存
function onSaveBLevel() {
  bFormRef.value.validate((valid: boolean) => {
    if (!valid) return;

    // 添加验证：至少选择一种计算方式
    if (bTypeBasis.value.length === 0) {
      ElMessage.error('请至少选择一种等级计算方式（累计充值金额或累计消费金额）');
      return;
    }

    // 添加金额区间验证逻辑
    const isValid = validateAmountRanges();
    if (!isValid) return;

    if (bForm.id) {
      // 编辑
      const idx = bLevelList.value.findIndex(l => l.id === bForm.id);
      if (idx > -1) bLevelList.value[idx] = JSON.parse(JSON.stringify(bForm));
      ElMessage.success('编辑成功');
    } else {
      // 新增
      bForm.id = Date.now();
      bLevelList.value.push(JSON.parse(JSON.stringify(bForm)));
      ElMessage.success('新增成功');
    }
    showBForm.value = false;
  });
}

// 添加B类等级金额区间验证函数
function validateAmountRanges() {
  // 创建临时列表，包含当前表单数据
  let tempList = [...bLevelList.value];
  if (bForm.id) {
    // 编辑模式，替换原有数据
    const idx = tempList.findIndex(l => l.id === bForm.id);
    if (idx > -1) {
      tempList[idx] = JSON.parse(JSON.stringify(bForm));
    }
  } else {
    // 新增模式，添加新数据
    tempList.push(JSON.parse(JSON.stringify(bForm)));
  }

  // 按minAmount排序
  tempList.sort((a, b) => a.minAmount - b.minAmount);

  // 检查重叠和中断（类似validateExpRanges的实现）
  for (let i = 0; i < tempList.length; i++) {
    const current = tempList[i];
    
    // 检查当前区间是否有效
    if (current.maxAmount !== null && current.minAmount >= current.maxAmount) {
      ElMessage.error(`等级${current.name}的最小金额不能大于或等于最大金额`);
      return false;
    }

    // 检查与下一个区间是否重叠或中断
    if (i < tempList.length - 1) {
      const next = tempList[i + 1];
      
      // 如果当前区间有上限
      if (current.maxAmount !== null) {
        // 检查重叠 - 不允许保存
        if (next.minAmount < current.maxAmount) {
          ElMessage.error(`等级${current.name}和等级${next.name}的区间存在重叠，请调整`);
          return false;
        }
        
        // 检查中断 - 只提示，允许保存
        if (next.minAmount > current.maxAmount) {
          ElMessage.warning(`等级${current.name}和等级${next.name}的区间存在中断（${current.maxAmount}万円 - ${next.minAmount}万円）`);
        }
      }
    }
  }

  // 存在中断但没有重叠，允许保存
  return true; // 简化处理，实际应返回验证结果
}
</script>

<style scoped>
.toolbar {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
}

.toolbar-left {
  display: flex;
  gap: 12px;
}

.toolbar-right {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.mr-4 {
  margin-right: 8px;
}
.avatar-uploader {
  display: inline-block;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}
.avatar {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  background: #f0f2f5;
  color: #909399;
  font-size: 18px;
}

.rights-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.right-item {
  background: #f0f2f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}
</style>